package com.fishingwithme.domain.spots;


import com.fishingwithme.infrastructure.CodeEnum;
import com.fishingwithme.infrastructure.utils.CommonUtils;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.Getter;
import org.json.JSONException;

import java.util.HashMap;
import java.util.Map;

@Getter
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
//@JsonSerialize(using = CodeEnumSerializer.class)
public enum ParkingDistance implements CodeEnum {
    TEN_MITRES(1, 10, "10米"),
    FIFTY_MITRES(2, 50, "50米"),
    HUNDRED_MITRES(3, 100, "100米"),
    TWO_HUNDRED_MITRES(4, 200, "200米"),
    FIVE_HUNDRED_MITRES(5, 500, "500米"),
    OTHER(6, 10000, "其他");
    @JsonProperty("type")
    private int type;
    @JsonProperty("distance")
    private int distance;
    @JsonProperty("name")
    private String name;

    ParkingDistance(int type, int distance, String name) {
        this.type = type;
        this.distance = distance;
        this.name = name;
    }

    // 重写 toString() 方法，返回 JSON 格式
    @Override
    public String toString() {
        try {
            return toJson().toString();
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

    // 返回 JSON 对象
    public ObjectNode toJson() throws JSONException {
        ObjectNode json = CommonUtils.objectMapper.createObjectNode();
        json.put("code", this.name());
        json.put("type", this.type);
        json.put("name", this.name);
        return json;
    }



    // 根据 type 查找枚举
    private static final Map<Integer, ParkingDistance> TYPE_MAP = new HashMap<>();

    static {
        for (ParkingDistance dist : values()) {
            TYPE_MAP.put(dist.type, dist);
        }
    }

    public static ParkingDistance of(int type) {
        return TYPE_MAP.getOrDefault(type, null);
    }

    // 根据实际距离自动匹配枚举（例如：75米 -> HUNDRED_MITRES）
    public static ParkingDistance fromDistance(int metres) {
        for (ParkingDistance dist : values()) {
            if (metres <= dist.distance) {
                return dist;
            }
        }
        return OTHER;
    }
}
